﻿using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour
{
    //摄像机移动的最近,最远距离
    private float farDistance = -10;
    private float nearDistance = -3;
    public float CurrentDistance { get; private set; }
    private Transform targetCamera;
    public float moveSpeed = 3f;

    //摄像机旋转
    private float maxAngle = 45f;
    private float angleX, angleY;
    private float h, v;
    public float RotateSpeed = 5f;

    void Awake()
    {
        targetCamera = Camera.main.transform;     //获取摄像机
        Debug.Log(CurrentDistance);
    }

    void Start()
    {
        Init();
    }
    void Init()
    {
        angleX = transform.eulerAngles.x;
        angleY = transform.eulerAngles.y;
        CurrentDistance = targetCamera.transform.localPosition.z;
    }
    void LateUpdate () {
	    //移动
	    CameraMove();
	    //旋转
	    CameraRotate();
        Debug.Log(CurrentDistance + " : " + Input.GetAxis("Mouse ScrollWheel"));

	}

    void CameraRotate()
    {
        if (Input.GetMouseButton(1))
        {
            h = Input.GetAxis("Mouse X");       //水平
            v = Input.GetAxis("Mouse Y");       //垂直

            angleX -= v * RotateSpeed / 2;
            angleY += h * RotateSpeed / 2;

            angleX = Mathf.Clamp(angleX, -maxAngle, maxAngle);
        }
        Quaternion toRotation = Quaternion.Euler(angleX, angleY, 0);

        transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, Time.deltaTime * RotateSpeed);
    }

    void CameraMove()
    {
        CurrentDistance += Input.GetAxis("Mouse ScrollWheel");
        CurrentDistance = Mathf.Clamp(CurrentDistance, farDistance, nearDistance);
        targetCamera.localPosition = Mathf.Abs(targetCamera.localPosition.z - CurrentDistance) < 0.1f 
            ? new Vector3(0, 0, CurrentDistance) 
            :Vector3.Lerp(targetCamera.localPosition,
            new Vector3(0, 0, CurrentDistance),
            Time.deltaTime * moveSpeed);
    }
}
